<template>
  <el-dialog :title="showTilt" :visible="showDialog" @close="btnCancel">
    <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="roleForm.name" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="roleForm.description" />
      </el-form-item>
    </el-form>
    <!-- 底部 -->
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="btnCancel">取消</el-button>
        <el-button size="small" type="primary" @click="btnOK">确定</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { updateRole, addRole, getRoleDetail } from '@/api/setting'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      roleForm: {},
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    showTilt() {
      return this.roleForm.id ? '编辑角色' : '新增角色'
    }
  },
  methods: {
    // 编辑功能 获取部门详情
    async getRoleDetail(id) {
      // 调接口之后，数组直接绑定
      this.roleForm = await getRoleDetail(id)
    },
    btnOK() {
      this.$refs.roleForm.validate(async isOK => {
        if (isOK) {
          if (this.roleForm.id) {
            // 编辑
            await updateRole(this.roleForm)
          } else {
            // 新增
            await addRole(this.roleForm)
          }
          // 通知父组件重新拉取数据
          this.$emit('addRole')
          // 提示成功
          this.$message.success('操作成功')
          // 关闭弹层
          this.$emit('update:showDialog', false)
        }
      })
    },
    btnCancel() {
      // 重置数据
      this.roleForm = {
        name: '',
        description: ''
      }
      // 移除校验
      this.$refs.roleForm.resetFields()
      // 关闭弹层
      this.$emit('update:showDialog', false)
    }
  }
}
</script>

<style>

</style>
